package com.generate.tools.service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.generate.tools.utils.PropertiesUtil;
import com.generate.tools.utils.StringUtils;

public class GenerateEntityMysql implements IMaster {
	private static final Logger logger = LoggerFactory.getLogger(GenerateEntityMysql.class);
	private String packageOutPath = PropertiesUtil.read("entityPath", PRO_CONFIG);// 指定实体生成所在包的路径
	private String authorName = PropertiesUtil.read("authorName", PRO_CONFIG);// 作者名字
	private String[] colnames; // 列名数组
	private String[] colTypes; // 列名类型数组
	private int[] colSizes; // 列名大小数组
	private boolean f_util = false; // 是否需要导入包java.util.*
	private boolean f_sql = false; // 是否需要导入包java.sql.*
	private String tableName = "";
	private static final String PRO_CONFIG = "gen";

	public Map<String, String> getColumnCommentMap(Connection conn, String tablename) {
		try {
			String sql = "select COLUMN_COMMENT,COLUMN_NAME,TABLE_NAME from   Information_schema.columns c where c.table_name=?";
			PreparedStatement pStemt = conn.prepareStatement(sql);
			pStemt.setString(1, tablename);
			ResultSet rs = pStemt.executeQuery();
			Map<String, String> map = new HashMap<String, String>();
			while (rs.next()) {
				map.put(rs.getString("TABLE_NAME") + rs.getString("COLUMN_NAME"), rs.getString("COLUMN_COMMENT"));
			}
			return map;
		} catch (Exception e) {
			return new HashMap<String, String>();
		}
	}
	
	public Map<String, String> getTableCommentMap(Connection conn, String tablename) {
		try {
			String sql = "select TABLE_COMMENT,TABLE_NAME from   Information_schema.tables c where c.table_name=?";
			PreparedStatement pStemt = conn.prepareStatement(sql);
			pStemt.setString(1, tablename);
			ResultSet rs = pStemt.executeQuery();
			Map<String, String> map = new HashMap<String, String>();
			while (rs.next()) {
				map.put(rs.getString("TABLE_NAME") , rs.getString("TABLE_COMMENT"));
			}
			return map;
		} catch (Exception e) {
			return new HashMap<String, String>();
		}
	}

	/*
	 * 构造函数
	 */
	public void generate(Connection conn) {
		String tableNameStr = PropertiesUtil.read("tableName", PRO_CONFIG);
		logger.info("table:" + tableNameStr);
		List<String> tableNames = Arrays.asList(tableNameStr.split(","));
		// 查要生成实体类的表
		PreparedStatement pStemt = null;
		try {
			for (String name : tableNames) {
				Map<String, String> commentMap = getColumnCommentMap(conn, name);
				Map<String, String> tableCommentMap = getTableCommentMap(conn, name);
				tableName = name;
				String sql = "select * from " + tableName;
				pStemt = conn.prepareStatement(sql);
				ResultSetMetaData rsmd = pStemt.getMetaData();
				int size = rsmd.getColumnCount(); // 统计列
				colnames = new String[size];
				colTypes = new String[size];
				colSizes = new int[size];
				for (int i = 0; i < size; i++) {
					colnames[i] = rsmd.getColumnName(i + 1);
					colTypes[i] = rsmd.getColumnTypeName(i + 1);
					if (colTypes[i].equalsIgnoreCase("datetime") || colTypes[i].equalsIgnoreCase("timestamp")) {
						f_util = true;
					}
					if (colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")) {
						f_sql = true;
					}
					colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
				}
				final String content = parse(colnames, colTypes, colSizes, commentMap,tableCommentMap);
				logger.info("content:"+content);
				String absolutePath = getAbsolutePath() + PropertiesUtil.read("projectStructure", PRO_CONFIG)
						+ this.packageOutPath.replace(".", File.separator) + File.separator;
				String outputPath = absolutePath + StringUtils.upperCase(getClassName(tableName)) + ".java";
				File file = new File(absolutePath);
				if (!file.exists()) {
					file.mkdirs();
				}
				FileWriter fw = new FileWriter(outputPath);
				PrintWriter pw = new PrintWriter(fw);
				pw.println(content);
				pw.flush();
				pw.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				pStemt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		logger.info("end.");
	}

	private String getAbsolutePath() {
		File directory = new File("");
		String path = PropertiesUtil.read("absolutePath", PRO_CONFIG);
		if (path != null && !"".equals(path)) {
			return path;
		}
		return directory.getAbsolutePath();

	}

	/**
	 * 功能：生成实体类主体代码
	 * 
	 * @param colnames
	 * @param colTypes
	 * @param colSizes
	 * @return
	 */
	private String parse(String[] colnames, String[] colTypes, int[] colSizes, Map<String, String> commentMap,Map<String, String> tableCommentMap) {
		StringBuffer sb = new StringBuffer();

		sb.append("package " + this.packageOutPath + ";\r\n");

		// 判断是否导入工具包
		if (f_util) {
			sb.append("import java.util.Date;\r\n");
		}
		if (f_sql) {
			sb.append("import java.sql.*;\r\n");
		}
		if ("true".equals(PropertiesUtil.read("annotation", PRO_CONFIG))) {
			sb.append("import com.quick.mybatis.annotation.*;\r\n");
			sb.append("import com.quick.mybatis.constants.JavaType;\r\n");
			sb.append("import org.apache.ibatis.type.JdbcType;\r\n");
		}

		sb.append("\r\n");
		// 注释部分
		sb.append("   /**\r\n");
		sb.append("    * " +tableCommentMap.get(tableName)+ "\r\n");
		sb.append("    * " + new Date() + " \r\n \t  author  " + this.authorName + "\r\n");
		sb.append("    */ \r\n");
		// 实体部分
		if ("true".equals(PropertiesUtil.read("annotation", PRO_CONFIG))) {
			sb.append("@Table(tableName = \"" + tableName + "\" )");
		}
		sb.append("\npublic class " + StringUtils.upperCase(getClassName(tableName)) + "{\r\n");
		processAllAttrs(sb, commentMap);// 属性
		processAllMethod(sb);// get set方法
		sb.append("}\r\n");
		return sb.toString();
	}
	
	private String getClassName(final String tableName){
		StringBuilder sb = new StringBuilder(tableName);
		String prefix = PropertiesUtil.read("prefix", PRO_CONFIG);
		if(tableName.startsWith(prefix)){
			sb.delete(0, prefix.length());
		}
		return StringUtils.getColumnName(String.valueOf(sb));
	}

	/**
	 * 功能：生成所有属性
	 * 
	 * @param sb
	 */
	private void processAllAttrs(StringBuffer sb, Map<String, String> commentMap) {

		for (int i = 0; i < colnames.length; i++) {
			sb.append("\t/**").append(commentMap.get(tableName + colnames[i])).append("**/\r\n");
			if ("true".equals(PropertiesUtil.read("annotation", PRO_CONFIG))) {
				sb.append("\t@Column(columnName=\""
						+ colnames[i] + "\"");
				sb.append(",javaType=JavaType." + sqlType2JavaType(colTypes[i]).toUpperCase());
				sb.append(",jdbcType=JdbcType." + sqlType2JdbcType(colTypes[i]) + getPrimaryKey(i) + ")\r\n");
			}
			sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " "
					+ StringUtils.getColumnName(StringUtils.lowerCase(colnames[i])) + ";\r\n");
		}

	}

	/**
	 * 功能：生成所有方法
	 * 
	 * @param sb
	 */
	private void processAllMethod(StringBuffer sb) {

		for (int i = 0; i < colnames.length; i++) {
			sb.append("\tpublic void set" + StringUtils.getColumnName(StringUtils.upperCase(colnames[i])) + "("
					+ sqlType2JavaType(colTypes[i]) + " "
					+ StringUtils.getColumnName(StringUtils.lowerCase(colnames[i])) + "){\r\n");
			sb.append("\t  this." + StringUtils.getColumnName(StringUtils.lowerCase(colnames[i])) + "="
					+ StringUtils.getColumnName(StringUtils.lowerCase(colnames[i]) + ";\r\n"));
			sb.append("\t}\r\n");
			sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get"
					+ StringUtils.getColumnName(StringUtils.upperCase(colnames[i]) + "(){\r\n"));
			sb.append("\t  return " + StringUtils.getColumnName(StringUtils.lowerCase(colnames[i]) + ";\r\n"));
			sb.append("\t}\r\n");
		}

	}

	private String getPrimaryKey(int index) {
		if (index == 0) {
			return ",primaryKey=true";
		}
		return "";
	}

	/**
	 * 功能：获得列的数据类型
	 * 
	 * @param sqlType
	 * @return
	 */
	private String sqlType2JavaType(String sqlType) {
		if (sqlType.equalsIgnoreCase("bit")) {
			return "Boolean";
		} else if (sqlType.equalsIgnoreCase("tinyint")) {
			return "Byte";
		} else if (sqlType.equalsIgnoreCase("smallint")) {
			return "Short";
		} else if (sqlType.equalsIgnoreCase("int")) {
			return "Integer";
		} else if (sqlType.equalsIgnoreCase("bigint")) {
			return "Long";
		} else if (sqlType.equalsIgnoreCase("float")) {
			return "Float";
		} else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
				|| sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
				|| sqlType.equalsIgnoreCase("smallmoney")) {
			return "Double";
		} else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
				|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
				|| sqlType.equalsIgnoreCase("text")) {
			return "String";
		} else if (sqlType.equalsIgnoreCase("datetime") || sqlType.equalsIgnoreCase("timestamp")) {
			return "Date";
		} else if (sqlType.equalsIgnoreCase("image")) {
			return "Blod";
		}
		return null;
	}

	private String sqlType2JdbcType(String sqlType) {
		if (sqlType.equalsIgnoreCase("bit")) {
			return "BIT";
		} else if (sqlType.equalsIgnoreCase("tinyint")) {
			return "TINYINT";
		} else if (sqlType.equalsIgnoreCase("smallint")) {
			return "SMALLINT";
		} else if (sqlType.equalsIgnoreCase("int")) {
			return "INTEGER";
		} else if (sqlType.equalsIgnoreCase("bigint")) {
			return sqlType.toUpperCase();
		} else if (sqlType.equalsIgnoreCase("float")) {
			return sqlType.toUpperCase();
		} else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
				|| sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
				|| sqlType.equalsIgnoreCase("smallmoney")) {
			return sqlType.toUpperCase();
		} else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
				|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
				|| sqlType.equalsIgnoreCase("text")) {
			return "VARCHAR";
		} else if (sqlType.equalsIgnoreCase("timestamp")) {
			return "TIMESTAMP";
		} else if (sqlType.equalsIgnoreCase("datetime")) {
			return "DATE";
		} else if (sqlType.equalsIgnoreCase("image")) {
			return "IMAGE";
		}
		return null;
	}

}
